package com.boyan.auth.interceptor;

import com.boyan.auth.domain.holder.UserHolder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.判断是否需要拦截（ThreadLocal中是否有用户）
        //log.info(UserHolder.getUser().getPhone());
        if (UserHolder.getUser() == null) {
            log.info("用户未登录，拦截请求：{}", request.getRequestURI());
            // 没有，需要拦截，设置状态码
            response.setStatus(401);
            // 拦截
            return false;
        }
        log.info("用户已登录，放行请求：{}", request.getRequestURI());
        // 有用户，则放行
        return true;
    }
}
